import {Outlet, useNavigate } from "react-router-dom";

import React, { useEffect, useState,useRef } from 'react';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UploadOutlined,
  UserOutlined,
  DownOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons';
// 导入所有,名称为Icon
import * as Icon from '@ant-design/icons'
import { Layout, Menu, Button, theme ,Tabs,Avatar,Dropdown} from 'antd';
 

type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

const { Header, Sider, Content } = Layout;

// console.log("menu",menu)
function mapMenu(list:any){

  
  // 遍历list 如果有children,递归遍历,
  // list.map从现有的数组映射为新的数组
  return list.map((item:any)=>{
    const obj:any = {key:item.path.slice(7),label:item.name};
    if(item.icon2){ 
      // (Icon as any) 把Icon 类型定义any
      //  React.createElement 通过react对象或者字符串创建节点
        obj.icon = React.createElement((Icon as any)[item.icon2])
    }
    if(item.children){
      // 递归映射子节点
      obj.children = mapMenu(item.children)
    }
    // 
    return obj;
  })
 
}


const AdminView: React.FC = () => {
  // 用户信息
  const userInfo = JSON.parse(sessionStorage.getItem("user")||"{}");
  const menu = JSON.parse(sessionStorage.getItem("menu")||"[]");
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const navigate = useNavigate()
 const menuClick = (e:any)=>{
  navigate(e.key)
  const item = items.find((it:any)=>it.key==e.key);
  if(!item){
    // 如果没有就添加
    items.push({key:e.key,label:e.domEvent.target.innerText})
    setItems([...items])
  }
 
  setActiveKey(e.key);
  // 存储tabs
  sessionStorage.setItem("tabs",JSON.stringify(items));
  // 存储key
  sessionStorage.setItem("activeKey",e.key);
 }
 useEffect(()=>{
  // 如果已经刷新就什么也不做,没有刷新过,刷新一遍
  if(!sessionStorage.getItem("isRefresh")){
    sessionStorage.setItem("isRefresh","1");
    location.reload();//刷新
  }
  // 跳转到admin/dash 默认页面
  if(location.pathname=="/admin"){
    navigate(activeKey);
  }
 
 },[])
// -----------------------标签处理
// 获取默认标签(默认是dash,不能删除)
const defaultPanes = JSON.parse(sessionStorage.getItem("tabs")||`[{"key":"dash","label":"概况", "closable": false}]`)
// items是表情数据
const [items, setItems] = useState(defaultPanes);
// 当前激活标签key
const [activeKey, setActiveKey] = useState(sessionStorage.getItem('activeKey')|| defaultPanes[0].key);

 

const onChange = (key: string) => {
  setActiveKey(key);  //更新key
  navigate(key)// 跳转对应页面
  sessionStorage.setItem("activeKey",key); //存储key
};

 

const remove = (targetKey: TargetKey) => {
  // 获取点击删除的tab的下标
  const targetIndex = items.findIndex((pane:any) => pane.key === targetKey);
  // 过滤出新的tabs  如果key不等于要删除targetKey 就保留
  const newPanes = items.filter((pane:any) => pane.key !== targetKey);
  // 如果新的tabs有长度并且 targetKey等于activeKey(删除的标签就是当前显示的子路由)
  if (newPanes.length && targetKey === activeKey) {
    // 从获取的对对象中结构处key
    // 对象取newPannes(新的tabs)中的一个 如果删除的下标等于newPanes长度 就取targetIndex前一个,否则就取targetIndex个
    // (如果删除的前面的key,没有前面的key就取最后一个)
    const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
    setActiveKey(key);
    navigate(key);
    sessionStorage.setItem("activeKey",key);
  }
  sessionStorage.setItem("tabs",JSON.stringify(newPanes))

  setItems(newPanes);
};

const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
  if (action === 'add') {
    // add();
  } else {
    remove(targetKey);
  }
};

// -----------------------标签处理ed
const logout = ()=>{
  sessionStorage.clear();
  navigate("/")
}

  return (
    <Layout className={collapsed?'adminView collapsed':'adminView'}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="demo-logo-vertical" />
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['1']}
          onClick={menuClick}
          items = {mapMenu(menu)}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }} className="header">
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />
          <div className="right">
          <Avatar src={userInfo.avatar}  icon={<UserOutlined />}/>
          <Dropdown menu={{ items:[
            {key:"1",label:<p>积分:{userInfo.score}</p>},
            {key:"2",label:<p onClick={logout}>退出</p>},
          ] }}>
            <a  style={{color:"#000",position:"relative"}}> {userInfo.name} <DownOutlined /> </a>           
          </Dropdown>
          </div>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
          }}
        >

            <Tabs
        hideAdd
        onChange={onChange}
        activeKey={activeKey}
        type="editable-card"
        onEdit={onEdit}
        items={items}
      />
          <Outlet/>
        </Content>
      </Layout>
    </Layout>
  );
};

export default AdminView;